package com.sqx.modules.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserCertificationDao;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.entity.UserCertification;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.response.HomeMessageResponse;
import com.sqx.modules.app.response.UserMessageResponse;
import com.sqx.modules.app.service.UserCertificationService;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.pay.service.CashOutService;
import com.sqx.modules.pay.service.PayDetailsService;
import com.sqx.modules.taking.entity.OrderTaking;
import com.sqx.modules.taking.service.OrderTakingService;
import com.sqx.modules.task.entity.HelpOrder;
import com.sqx.modules.task.service.HelpOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fang
 * @date 2020/7/30
 */
@RestController
@Api(value = "用户管理", tags = {"用户管理"})
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private PayDetailsService payDetailsService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UserCertificationService certificationService;
    @Autowired
    private OrderTakingService takingService;
    @Autowired
    private CashOutService cashOutService;
    @Autowired
    private UserCertificationDao userCertificationDao;



    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    @ApiOperation("获取用户详细信息")
    @ResponseBody
    public Result selectUserById(@ApiParam("用户id") @PathVariable Long userId) {
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = userService.queryByUserId(userId);
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        Double money = 0.0;
        BigDecimal safetyMoney = BigDecimal.ZERO;
        if (userMoney != null) {
            money = userMoney.getMoney().doubleValue();
            safetyMoney = userMoney.getSafetyMoney();
        }
        //查询用户钱包
        Double m = money;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        //查询本月充值
        Double consume = payDetailsService.instantselectSumPay(date, userId);
        //查询本月提现
        Double income = cashOutService.selectCashOutSum(userId,date);
//        Double income = userMoneyDetailsService.monthIncome(date, userId);
        //查询邀请人数
        int count = userService.queryInviterCount(userEntity.getInvitationCode());
        //本月接单
        int takeOrdersCount = ordersService.selectTakeOrdersCount(userId, date);
        //本月订单
        int myOrdersCount = ordersService.selectMyOrdersCount(userId, date);
        if(userEntity.getCompanyId()!=null){
            UserCertification userCertification = userCertificationDao.selectOne(new QueryWrapper<UserCertification>().eq("user_id", userEntity.getCompanyId()));
            if(userCertification!=null){
                userEntity.setCompanyName(userCertification.getShopName());
            }
        }
        map.put("userEntity", userEntity);
        map.put("money", m);
        map.put("safetyMoney", safetyMoney);
        map.put("consume", consume);
        map.put("income", income);
        map.put("count", count);
        map.put("takeOrdersCount", takeOrdersCount);
        map.put("myOrdersCount", myOrdersCount);
        return Result.success().put("data", map);
    }

    @RequestMapping(value = "/addCannotMoney/{userId}/{money}/{type}", method = RequestMethod.POST)
    @ApiOperation("修改金额")
    @ResponseBody
    public Result addCannotMoney(@PathVariable("userId") Long userId, @PathVariable("money") Double money, @PathVariable("type") Integer type) {
        if (type == 1) {
            userMoneyService.updateMoney(1, userId, BigDecimal.valueOf(money));
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setMoney(BigDecimal.valueOf(money));
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("管理端充值：" + money);
            userMoneyDetails.setTitle("管理端充值金额");
            userMoneyDetails.setType(1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
        } else {
            userMoneyService.updateMoney(2, userId, BigDecimal.valueOf(money));
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setMoney(BigDecimal.valueOf(money));
            userMoneyDetails.setUserId(userId);
            userMoneyDetails.setContent("管理端减少：" + money);
            userMoneyDetails.setTitle("管理端减少金额");
            userMoneyDetails.setType(2);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
        }
        return Result.success();
    }


    @RequestMapping(value = "/selectUserList", method = RequestMethod.GET)
    @ApiOperation("查询所有用户列表")
    @ResponseBody
    public Result selectUserList(Integer page, Integer limit,
                                 String phone,
                                 Integer sex,
                                 String platform,
                                 String sysPhone,
                                 Integer status,
                                 Long companyId,
                                 Integer isAuthentication, String userName,
                                 String phoneAndUserName,
                                 Integer isCompany,
                                 Integer shopType, String companyName,
                                 String invitationCode,
                                 String inviterCode,
                                 Integer isVip
    ) {
        return userService.selectUserPage(page, limit, phone, sex, platform, sysPhone, status, companyId, isAuthentication, userName, phoneAndUserName, isCompany, shopType, companyName, invitationCode, inviterCode, isVip);
    }

    /**
     * 查看员工列表
     *
     * @return
     */
    @GetMapping("getWorkerUserList")
    public Result getWorkerUserList(Integer page, Integer limit, Long companyId, Integer sex, Integer workStatus, String phone, String userName) {
        return Result.success().put("data", userService.getWorkerUserList(page, limit, companyId, sex, workStatus, phone, userName));
    }

    @RequestMapping(value = "/deleteUserByUserId/{userId}", method = RequestMethod.POST)
    @ApiOperation("删除用户")
    @ResponseBody
    public Result deleteUserByUserId(@PathVariable("userId") Long userId) {
        userService.removeById(userId);
        return Result.success();
    }

    @RequestMapping(value = "/updateUserByUserId", method = RequestMethod.POST)
    @ApiOperation("修改用户")
    @ResponseBody
    public Result updateUserByUserId(@RequestBody UserEntity userEntity) {
        if (StringUtils.isNotBlank(userEntity.getPhone())) {
            int count = userService.count(new QueryWrapper<UserEntity>().eq("phone", userEntity.getPhone()).ne("user_id", userEntity.getUserId()));
            if (count >= 1) {
                return Result.error("当前手机号已存在");
            }
        }
        userService.updateById(userEntity);
        return Result.success();
    }

    @RequestMapping(value = "/updateUserStatusByUserId", method = RequestMethod.GET)
    @ApiOperation("禁用或启用用户")
    @ResponseBody
    public Result updateUserByUserId(Long userId) {
        UserEntity byId = userService.getById(userId);
        if (byId.getStatus().equals(1)) {
            int count = takingService.count(new QueryWrapper<OrderTaking>().eq("user_id", userId).eq("status", 0));
            if (count > 0) {
                return Result.error("当前商家下还有服务尚未下架,请先处理");
            }
            byId.setStatus(2);
        } else {
            byId.setStatus(1);
        }
        userService.updateById(byId);
        return Result.success();
    }


    /**
     * 获取openid
     *
     * @param code 微信code
     * @return openid
     */
    @GetMapping("/openId/{code:.+}/{userId}")
    @ApiOperation("根据code获取openid")
    public Result getOpenid(@PathVariable("code") String code, @PathVariable("userId") Long userId) {
        return userService.getOpenId(code, userId);
    }

    @GetMapping("selectUserByInvitationCode")
    @ApiOperation("根据邀请码查询用户")
    public Result selectUserByInvitationCode(String invitationCode) {
        return Result.success().put("data", userService.getOne(new QueryWrapper<UserEntity>().eq("invitation_code", invitationCode)));
    }

    /**
     * 信息分析
     *
     * @return
     */
    @GetMapping("/homeMessage")
    @ApiOperation("信息分析")
    public Result homeMessage() {
        HomeMessageResponse homeMessageResponse = new HomeMessageResponse();
        //   0查总   1查天  2查月  3查年
        //设置总用户人数
        homeMessageResponse.setTotalUsers(userService.queryUserCount(0, null));
        //设置今日新增
        homeMessageResponse.setNewToday(userService.queryUserCount(1, null));
        //设置本月新增
        homeMessageResponse.setNewMonth(userService.queryUserCount(2, null));
        //设置本年新增
        homeMessageResponse.setNewYear(userService.queryUserCount(3, null));

        //设置总收入
        homeMessageResponse.setTotalRevenue(userService.queryPayMoney(0));
        //设置今日收入
        homeMessageResponse.setTodayRevenue(userService.queryPayMoney(1));
        //设置本月收入
        homeMessageResponse.setMonthRevenue(userService.queryPayMoney(2));
        //设置本年收入
        homeMessageResponse.setYearRevenue(userService.queryPayMoney(3));

        return Result.success().put("data", homeMessageResponse);
    }

    /**
     * 接单分析
     *
     * @return
     */
    @GetMapping("/takingOrdersMessage")
    @ApiOperation("接单分析")
    public Result takingOrdersMessage(Long page, Long limit, String date, Long type) {
        Page<Map<String, Object>> iPage = new Page<>(page, limit);
        return userService.takingOrdersMessage(iPage, type, date);
    }

    /**
     * 用户分析
     */
    @GetMapping("/userMessage")
    @ApiOperation("用户分析")
    public Result userMessage(String date, int type) {
        UserMessageResponse userMessageResponse = new UserMessageResponse();
        userMessageResponse.setTotalNumber(userService.queryUserCount(type, date));
        userMessageResponse.setVipUserNumber(userService.userMessage(date, type));
        userMessageResponse.setUserNumber(userService.queryUserCount(type, date) - userService.userMessage(date, type));
        return Result.success().put("data", userMessageResponse);
    }

    @ApiOperation("用户统计分析")
    @GetMapping("/getUserStatistics")
    public Result getUserStatistics(String time, Integer flag) {
        return Result.success().put("data", ordersService.getUserStatistics(time, flag));
    }

    @ApiOperation("赠送用户会员")
    @PostMapping("/giveUserVip")
    public Result giveUserVip(Long userId, Integer type, Integer day) {
        return userService.giveUserVip(userId, type, day);
    }


    @ApiOperation("修改用户实名信息")
    @PostMapping("/updateCertification")
    public Result updateCertification(@RequestBody UserCertification userCertification) {
        return certificationService.updateCertification(userCertification);
    }

    @PostMapping("/updateSafetyMoney")
    @ApiOperation("修改")
    public Result updateSafetyMoney(Long userId, Integer type, BigDecimal money) {
        userMoneyService.updateSafetyMoney(type, userId, money);
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        userMoneyDetails.setClassify(5);
        userMoneyDetails.setUserId(userId);
        if (type == 1) {
            userMoneyDetails.setTitle("[保证金]增加保证金");
            userMoneyDetails.setContent("系统增加保证金");
        } else {
            userMoneyDetails.setTitle("[保证金]减少保证金");
            userMoneyDetails.setContent("系统减少保证金");
        }
        userMoneyDetails.setType(type);
        userMoneyDetails.setMoney(money);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userMoneyDetails.setCreateTime(sdf.format(new Date()));
        userMoneyDetailsService.save(userMoneyDetails);
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userId);
        UserEntity userEntity = userService.getById(userId);
        CommonInfo safetyMoney = commonInfoService.findOne(616);
        if (userMoney.getSafetyMoney().compareTo(new BigDecimal(safetyMoney.getValue())) >= 0) {
            userEntity.setIsSafetyMoney(1);
        } else {
            userEntity.setIsSafetyMoney(0);
        }
        userService.updateById(userEntity);
        return Result.success();
    }

    @GetMapping("/getSafetyMoneyData")
    @ApiOperation("获取保证金金额")
    public Result getSafetyMoneyData(Integer flag, String time) {
        return Result.success().put("data", userMoneyService.getSafetyMoneyData(flag, time));
    }

}